<template>
  <div class="page-content">
    <MenuBar v-if="!isMobile" passTab="1" />

    <PhoneMenuBar v-else passTab="1"/>



    <div class="page-product">

      <div class="product-title">产品中心</div>

      <div class="page-filter">

        <span class="condition">按类别</span>

        <div class="product-list" v-if="!isMobile">
          <div class="product-item"
            :style="{ 'background-color': typeId == item.id ? '#787575' : '#ebebeb', 'color': typeId == item.id ? '#ffffff' : '#111111' }"
            @click="chooseCategory(item.id)" v-for="item in c_productList" :key="item.id">{{
              item.name }}</div>
        </div>

        <n-select class="select-text" @update:value="handleUpdateCategory" v-model:value="typeId"
          :options="c_productList" v-else />
      </div>

      <div class="page-filter">

        <span class="condition">按排序</span>

        <div class="product-list" v-if="!isMobile">
          <div class="product-item"
            :style="{ 'background-color': sorType == item.value ? '#787575' : '#ebebeb', 'color': sorType == item.value ? '#ffffff' : '#111111' }"
            @click="chooseSortType(item.value)" v-for="item in sortList" :key="item.value">{{
              item.label }}</div>
        </div>

        <n-select class="select-text" @update:value="handleUpdateSortType" v-model:value="sorType" :options="sortList"
          v-else />
      </div>

      <div style="display: flex;justify-content: center;margin-top: 15px;" v-if="!isMobile">
        <n-pagination class="pagination" v-model:page="pageNum" :page-count="totalNum" :page-sizes="[pageSize]"
          size="large" @update:page="handlePageChange" :theme-overrides="paginationThemeOverrides" show-quick-jumper />
      </div>

      <div class="toy-layout">


        <div class="toy-list">
          <div class="toy-item" v-for="(item) in all_productList" :key="item.id" @click="openProductInfoPage(item.id)">

            <div class="product-image">
              <img :src="item.imgurl" class="toy-img" />
            </div>

            <div class="toy-content">
              <span class="toy-label">{{ item.prop_list != null && item.prop_list.length != 0 ?
                (item.prop_list[0]["value"]
                  || '暂无') : '暂无'
              }}</span>
              <span class="toy-name">{{ item.title }}</span>
              <div class="toy-bottom">
                <span class="toy-no">货号{{ item.prop_list != null && item.prop_list.length != 0 ?
                  (item.prop_list[3]["value"]
                    || '-') : '-'
                }}</span>
                <span class="toy-money">{{ item.prop_list != null && item.prop_list.length != 0 ?
                  (item.prop_list[2]["value"] || '-') : '-'
                }}円</span>
              </div>

            </div>

          </div>
        </div>
      </div>


      <div style="display: flex;justify-content: center;margin-top: 15px;" v-if="!isMobile">
        <n-pagination class="pagination" v-model:page="pageNum" :page-count="totalNum" :page-sizes="[pageSize]"
          size="large" @update:page="handlePageChange1" :theme-overrides="paginationThemeOverrides" show-quick-jumper />
      </div>


      <div v-else style="display: flex;justify-content: space-between;align-items: center;margin-top: 15px;">

        <n-button type="info" @click="pageNumOnClick('-')" :style="{ visibility: pageNum != 1 ? 'visible' : 'hidden' }">
          上一页
        </n-button>

        <div style="width: 80px;"><n-select v-model:value="pageNum" @update:value="handlePageNumValue"
            :options="pageNumOptions" filterable /></div>

        <n-button type="info" @click="pageNumOnClick('+')" :style="{ visibility: pageNum != totalNum ? 'visible' : 'hidden' }">
          下一页
        </n-button>
      </div>

    </div>

    <BottomBar />
  </div>
</template>

<script setup name="productListPage">
import { API_URL } from '@/config'
import { productCategory, productList } from '@/api'
import { ref, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import MenuBar from '@/components/MenuBar.vue'
import PhoneMenuBar from '@/components/PhoneMenuBar.vue'
import BottomBar from '@/components/BottomBar.vue'
// 创建一个响应式变量来存储是否为移动设备
const isMobile = ref(false);

// 定义一个函数来检查用户代理
const checkDevice = () => {
  const userAgent = navigator.userAgent || navigator.vendor || window.opera;

  // 设置isMobile的值
  isMobile.value = /android/i.test(userAgent) || /iPhone|iPad|iPod/i.test(userAgent);

  console.log("product-isMobile", isMobile.value)
};

const sortList = [{ value: 1, label: '发布时间' }, { value: 2, label: '价格(从高到低)' }, { value: 3, label: '价格(从低到高)' }, { value: 4, label: '产品货号' }]

const typeId = ref("-1")
const sorType = ref(1)
const c_productList = ref([])
const getProductCategory = async () => {
  const result = await productCategory()

  if (isMobile.value) {
    const mapResult = result.data.map(bean => ({
      value: bean.id, label: bean.name
    }))
    c_productList.value = [{ value: "-1", label: "全部 All" }, ...mapResult]
  } else {

    c_productList.value = [{ id: "-1", name: "全部 All" }, ...result.data]
  }

  getProductList()
}

const all_productList = ref([])
const totalNum = ref(0)
const pageSize = 16
const getProductList = async () => {
  const params = {
    type_id: typeId.value == "-1" ? "" : typeId.value,
    page: pageNum.value,
    size: pageSize,
    sort_type: sorType.value,
  }
  const result = await productList(params)

  console.log("productList", result.data)

  if (result != null && result.data != null) {
    const list = result.data.map(item => {
      return {
        ...item,
        imgurl: item.imgurl?.startsWith('../') ? API_URL + item.imgurl.substring(2) : item.imgurl
      }
    })
    all_productList.value = list



    const totalCount = result.total;

    const fullPages = Math.floor(totalCount / pageSize); // 完整页数
    const remainder = totalCount % pageSize;             // 余数

    totalNum.value = remainder > 0 ? fullPages + 1 : fullPages;

    pageNumOptions.value = []
    for (let i = 1; i <= totalNum.value; i++) {
      pageNumOptions.value.push({ label: i + "", value: i + "" })
    }


  }


}

const route = useRoute()

onMounted(() => {
  checkDevice();

  const categoryId = route.query.typeId || "-1"
  typeId.value = categoryId

  getProductCategory()
});
const pageNum = ref(1)

function handleUpdateCategory(value, option) {
  chooseCategory(value)
}

const chooseCategory = async (categoryId) => {
  // console.log("chooseCategory", categoryId)
  typeId.value = categoryId;
  pageNum.value = 1;
  getProductList()
}

function handleUpdateSortType(value, option) {
  chooseSortType(value)
}

const chooseSortType = async (sort_type) => {
  // console.log("chooseCategory", categoryId)
  sorType.value = sort_type;
  pageNum.value = 1;
  getProductList()
}

const handlePageChange = (page) => {
  console.log('当前页:', page)
  // 在这里加载对应页的数据
  // pageNum.value = page;
  getProductList()
}

const handlePageChange1 = (page) => {
  console.log('当前页:', page)
  // 在这里加载对应页的数据
  // pageNum.value = page;
  getProductList()

  window.scrollTo({
    top: 0,
    behavior: 'smooth'  // 平滑滚动
  });
}

watch(
  () => route.query.typeId,
  (newId) => {
    typeId.value = newId || "-1"
    if (typeId.value != "-1") {
      console.log('typeId.value', typeId.value)
      getProductList()
    }

  },
  { immediate: true }
)

function pageNumOnClick(type) {

  if (type == "+") {
    pageNum.value++;
  } else {
    pageNum.value--;
  }

  getProductList()

  window.scrollTo({
    top: 0,
    // behavior: 'smooth'  // 平滑滚动
  });
}

function handlePageNumValue(e) {
  console.log("handlePageNumValue", pageNum.value)

  getProductList()

  window.scrollTo({
    top: 0,
    // behavior: 'smooth'  // 平滑滚动
  });
}

// 自定义分页主题样式
const paginationThemeOverrides = {

  // 👇 这些是官方支持的 overrides 属性
  itemColor: '#ffffff',                    // 默认背景
  itemColorHover: '#f0f0f0',               // 悬停背景
  itemColorActive: '#00aeff',              // 选中背景（蓝色）
  itemColorActiveHover: '#00aeff',         // 选中悬停
  textColor: '#333333',                    // 默认文字
  textColorActive: '#ffffff',              // ✅ 选中文字颜色（白色）
  itemBorder: '1px solid #d9d9d9',         // 边框
  itemBorderHover: '1px solid #00aeff',    // 悬停边框
  itemBorderActive: '1px solid #00aeff',   // 选中边框

}

const router = useRouter()
const openProductInfoPage = (pId) => {
  router.push({
    name: 'PInfo',
    query: {
      productId: pId
    }
  })
}

const pageNumOptions = ref([])

</script>

<style scoped lang="scss">
/* 容器样式 */
.page-content {
  width: 100vw;
  // height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;


  @media (min-width: 769px) {

    .page-product {
      margin-top: 70px;
      padding: 15px 120px;
      flex: 1;

      .product-title {
        color: #111111;
        font-size: 30px;
        font-weight: bold;
        line-height: 140%;
        margin-bottom: 15px;
      }

      .page-filter {
        display: flex;
        align-items: center;
        margin-top: 15px;
        background-color: white;
        padding: 10px 20px;
        height: 52px;


        .condition {
          color: #111111;
          font-size: 14px;
          margin-right: 50px;
          line-height: 130%;
          font-weight: bold;
        }

        .product-list {
          display: flex;
          gap: 10px;
          flex: 1;


          .product-item {
            font-size: 12px;
            font-weight: 700;
            padding: 4px;
            width: 100px;
            height: 36px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
            background-color: #5a5757;
            transition: background-color 0.3s ease;
            /* 平滑过渡效果 */
            cursor: pointer;
          }


          .product-item:hover {
            background-color: #787575;
          }
        }
      }


      .toy-layout {
        padding-top: 15px;
        margin: 0 auto;
        box-sizing: border-box;
        /* 确保padding不影响总宽度 */

        .toy-list {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
        }

        .toy-item {
          flex: 0 0 calc(25% - 8px * 3/4);
          /* 移动端默认占满一行 */
          display: flex;
          flex-direction: column;
          padding: 20px 15px;
          background: white;
          box-sizing: border-box;
          cursor: pointer;

          .toy-img {
            object-fit: cover;
            height: 192px;
            /* 新增：确保图片适应容器宽度 */
            width: 100%;
          }

          .toy-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            padding-top: 10px;
            width: 100%;

            .toy-label {
              margin-bottom: 7px;
              border: 1px #3A7BBF solid;
              color: #3A7BBF;
              font-size: 10px;
              width: fit-content;
              padding: 0px 20px;
            }


            .toy-name {
              font-weight: 500;
              color: black;
              font-size: 13px;
              line-height: 24px;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              line-clamp: 2;
              -webkit-box-orient: vertical;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: normal;
              /* 可省略，-webkit-line-clamp 会处理 */
              word-break: break-word;
              max-width: 100%;
              flex: 1;
            }

            .toy-bottom {
              margin-top: 12px;
              display: flex;
              justify-content: space-between;
              align-items: center;
              width: 100%;



              .toy-no {
                color: #5e7387;
                font-size: 13px;

              }

              .toy-money {
                color: #5e7387;
                font-size: 13px;
              }

            }


          }
        }
      }

    }
  }


  /* 手机端样式 */
  @media (max-width: 768px) {
    .page-product {
      margin-top: 70px;
      padding: 15px;


      .product-title {
        color: #111111;
        font-size: 18px;
        font-weight: bold;
        // margin-bottom: 15px;
      }

      .page-filter {
        display: flex;
        align-items: center;
        margin-top: 15px;
        background-color: white;
        padding: 15px;



        .condition {
          color: #111111;
          font-size: 14px;
          margin-right: 8px;
          width: 60px;
          font-weight: 500;
        }


      }

      .toy-layout {
        padding-top: 15px;
        margin: 0 auto;
        // width: 94%;
        box-sizing: border-box;
        /* 确保padding不影响总宽度 */

        .toy-list {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
        }

        .toy-item {
          flex: 0 0 calc(50% - 8px * 3/4);
          /* 移动端默认占满一行 */
          display: flex;
          flex-direction: column;
          padding: 10px;
          background: white;
          box-sizing: border-box;
          cursor: pointer;

          .toy-img {
            object-fit: contain;
            height: 120px;
            // max-height: 192px;
            /* 新增：确保图片适应容器宽度 */
            width: 100%;
          }

          .toy-content {
            display: flex;
            flex-direction: column;
            padding-top: 10px;

            .toy-label {
              margin-bottom: 7px;
              border: 1px #3A7BBF solid;
              color: #3A7BBF;
              font-size: 10px;
              width: fit-content;
              padding: 0px 20px;
            }


            .toy-name {
              font-weight: 500;
              color: black;
              font-size: 13px;
              line-height: 24px;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              line-clamp: 2;
              -webkit-box-orient: vertical;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: normal;
              /* 可省略，-webkit-line-clamp 会处理 */
              word-break: break-word;
              max-width: 100%;
              flex: 1;
            }

            .toy-bottom {
              margin-top: 8px;
              display: flex;
              justify-content: space-between;
              align-items: center;
              width: 100%;



              .toy-no {
                color: #5e7387;
                font-size: 13px;

              }

              .toy-money {
                color: #5e7387;
                font-size: 13px;
              }

            }


          }
        }
      }

    }
  }

  :deep(.n-pagination) {
    /* 强制重置所有 Pagination 相关变量 */
    --n-item-text-color-active: #ffffff !important;
    /* ✅ 关键：白色 */
    --n-item-text-color-hover: #333333 !important;
  }

}
</style>